package com.gengzi.upload.service;


import com.gengzi.upload.controller.UploadController;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 董诗攀
 */
@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg");

    public String uploadImage(MultipartFile file){
        //文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)) {
            LOGGER.info("文件上传失败:{},文件类型不合法！",originalFilename);
            return null;
        }

        try {
            //校验文件的内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                LOGGER.info("文件上传失败：{},文件内容不合法！",originalFilename);
                return null;
            }

            //保存到服务器
            //file.transferTo(new File("C:\\Users\\董诗攀\\Desktop\\hm53\\image\\"+originalFilename));

            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            //返回路径
            //return "http://image.gengzi.com/"+originalFilename;
            return "http://image.gengzi.com:8085/" + storePath.getFullPath();
        } catch (IOException e) {
            LOGGER.info("文件上传失败：{},服务器异常！",originalFilename);
            e.printStackTrace();

        }
        return null;
    }
}
